import Vue from "vue";
import Router from "vue-router";
import indexRouter from "@/router/modules/index";
// import localStorages from '@/utils/ControlTheCache'
// console.log(localStorages.get('routerNames'));

/**
 * hidden: true                   是否显示在侧边栏，true：不显示；false或者不填为显示
 * redirect: noredirect           if `redirect:noredirect` will no redirct in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
   role: ['admin','editor']     will control the page role (you can set multiple roles)
   title: 'title'               the name show in submenu and breadcrumb (recommend set)
   icon: 'svg-name'             the icon show in the sidebar,
   noCache: true                if fasle ,the page will no be cached(default is false)
 }
 **/

Vue.use(Router);
/* Layout */
// 把三级,四级菜单拍平成二级菜单
const handleRouter = function(routerArr) {
  for (const router of routerArr) {
    if (router.children) {
      for (const child of router.children) {
        if (child.children) {
          for (const grandson of child.children) {
            if (grandson.children) {
              child.children = child.children.concat(grandson.children);
              grandson.children.length = 0;
            }
          }
          router.children = router.children.concat(child.children);
          child.children.length = 0;
        }
      }
    }
  }

  return routerArr;
};
const synthesize = function(routers) {
  const syn = { constant: [], async: [] };
  for (let i = 0; i < routers.length; i++) {
    // handleRouter(routers[i].constantRouterMap);
    syn.constant = syn.constant.concat(routers[i].constantRouterMap);
    syn.async = syn.async.concat(routers[i].asyncRouterMap);
  }
  return syn;
};
const routerMap = synthesize([indexRouter]);
const copyConstantRouter = JSON.parse(JSON.stringify(routerMap.constant)); // 把原来的结构copy出来
export const constantRouterMap = copyConstantRouter;
export const asyncRouterMap = routerMap.async;

//混入beforeRouteEnter  为了拿到vm的实例调用刷新 所以用这种混入方式
Vue.mixin({
  beforeRouteEnter(to, from, next) {
    next(vm => {
      //是同一个模块并且来自新增和修改操作
      if (isCommModule(to, from) && isFromaddOrUpdate(from)) {
        vm.$root.$emit("refreshFn");
      }
    });
  }
});

//是否是相同模块的
function isCommModule(to, from) {
  let toPath = to.path.slice(0, to.path.lastIndexOf("/") + 1);
  let fromPath = from.path.slice(0, from.path.lastIndexOf("/") + 1);
  return toPath === fromPath;
}
//是否来着添加和更新的路由
function isFromaddOrUpdate(from) {
  return from.query.type == "add" || from.query.type == "update";
}

export default new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: handleRouter(routerMap.constant) // 把三级,四级菜单拍平成二级菜单
});
